{
 "cells": [
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2025-09-28T08:32:20.685689Z",
     "start_time": "2025-09-28T08:32:20.683447Z"
    }
   },
   "source": [
    "# pandas学习\n",
    "# pandas中Series的学习"
   ],
   "outputs": [],
   "execution_count": 1
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-09T09:08:29.060270Z",
     "start_time": "2025-10-09T09:08:25.039505Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "\n",
    "arr = np.array([1,3,3,np.nan,2])\n",
    "s = pd.Series(arr,index=['a','b','c','d','e'],name='num')\n",
    "print(s)"
   ],
   "id": "4129d4d6d049ca7d",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a    1.0\n",
      "b    3.0\n",
      "c    3.0\n",
      "d    NaN\n",
      "e    2.0\n",
      "Name: num, dtype: float64\n"
     ]
    }
   ],
   "execution_count": 3
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-28T08:59:53.079056Z",
     "start_time": "2025-09-28T08:59:53.073255Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#计算Series数组的常用方法\n",
    "print(s.index)\n",
    "print(s.keys())\n",
    "print(s.values)\n",
    "print(s.dtype)\n",
    "print(s.count())#获取数组的元素个数\n",
    "print(s.size)#获取数组的长度\n",
    "print(s.isnull())#判断是否为空\n",
    "print(s.isin([2,3,5]))#判断是否在列表中\n",
    "print(s.isna)#判断是否为空\n",
    "print(s.drop_duplicates())#删除重复的元素\n",
    "print(s.dropna())#删除为空的元素"
   ],
   "id": "2d9dfd3c08c53aa4",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Index(['a', 'b', 'c', 'd', 'e'], dtype='object')\n",
      "Index(['a', 'b', 'c', 'd', 'e'], dtype='object')\n",
      "[ 1.  3.  3. nan  2.]\n",
      "float64\n",
      "4\n",
      "5\n",
      "a    False\n",
      "b    False\n",
      "c    False\n",
      "d     True\n",
      "e    False\n",
      "Name: num, dtype: bool\n",
      "a    False\n",
      "b     True\n",
      "c     True\n",
      "d    False\n",
      "e     True\n",
      "Name: num, dtype: bool\n",
      "<bound method Series.isna of a    1.0\n",
      "b    3.0\n",
      "c    3.0\n",
      "d    NaN\n",
      "e    2.0\n",
      "Name: num, dtype: float64>\n",
      "a    1.0\n",
      "b    3.0\n",
      "d    NaN\n",
      "e    2.0\n",
      "Name: num, dtype: float64\n",
      "a    1.0\n",
      "b    3.0\n",
      "c    3.0\n",
      "e    2.0\n",
      "Name: num, dtype: float64\n"
     ]
    }
   ],
   "execution_count": 36
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-28T09:00:35.680931Z",
     "start_time": "2025-09-28T09:00:35.672108Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#Series数组的相关数学方法\n",
    "print(s.sum())\n",
    "print(s.max())\n",
    "print(s.min())\n",
    "print(s.mean())\n",
    "print(s.std())\n",
    "print(s.var())\n",
    "print(s.median())\n",
    "print(s.quantile(0.5))\n",
    "print(s.describe())\n",
    "print(s.cumsum())\n",
    "print(s.cumprod())\n",
    "print(s.values)\n",
    "print(s.unique())\n",
    "print(s.value_counts())\n",
    "print(s.sort_values())#排序按值\n",
    "print(s.sort_index())#排序按序号"
   ],
   "id": "486287ecc7774b94",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "9.0\n",
      "3.0\n",
      "1.0\n",
      "2.25\n",
      "0.9574271077563381\n",
      "0.9166666666666666\n",
      "2.5\n",
      "2.5\n",
      "count    4.000000\n",
      "mean     2.250000\n",
      "std      0.957427\n",
      "min      1.000000\n",
      "25%      1.750000\n",
      "50%      2.500000\n",
      "75%      3.000000\n",
      "max      3.000000\n",
      "Name: num, dtype: float64\n",
      "a    1.0\n",
      "b    4.0\n",
      "c    7.0\n",
      "d    NaN\n",
      "e    9.0\n",
      "Name: num, dtype: float64\n",
      "a     1.0\n",
      "b     3.0\n",
      "c     9.0\n",
      "d     NaN\n",
      "e    18.0\n",
      "Name: num, dtype: float64\n",
      "[ 1.  3.  3. nan  2.]\n",
      "[ 1.  3. nan  2.]\n",
      "num\n",
      "3.0    2\n",
      "1.0    1\n",
      "2.0    1\n",
      "Name: count, dtype: int64\n",
      "a    1.0\n",
      "e    2.0\n",
      "b    3.0\n",
      "c    3.0\n",
      "d    NaN\n",
      "Name: num, dtype: float64\n",
      "a    1.0\n",
      "b    3.0\n",
      "c    3.0\n",
      "d    NaN\n",
      "e    2.0\n",
      "Name: num, dtype: float64\n"
     ]
    }
   ],
   "execution_count": 38
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-28T09:20:39.301699Z",
     "start_time": "2025-09-28T09:20:39.294729Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#练习一\n",
    "arr = np.random.randint(50,101,10)\n",
    "indexs =[]\n",
    "for i in range(10):\n",
    "    indexs.append(\"学生\"+str(i+1))\n",
    "s = pd.Series(arr,index=indexs)\n",
    "print(s)\n",
    "print(f\"学生的平均分为{s.mean()}\")\n",
    "print(f\"学生的最大分为{s.max()}\")\n",
    "print(f\"学生的最小分为{s.min()}\")\n",
    "print(f\"高于平均分的学生\\n{s[s>s.mean()]}\")\n",
    "\n",
    "print(s.diff().abs().sort_values(ascending=False).index)#获取差值绝对值"
   ],
   "id": "467916f0d84defd6",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "学生1     55\n",
      "学生2     59\n",
      "学生3     52\n",
      "学生4     96\n",
      "学生5     92\n",
      "学生6     98\n",
      "学生7     74\n",
      "学生8     67\n",
      "学生9     56\n",
      "学生10    63\n",
      "dtype: int32\n",
      "学生的平均分为71.2\n",
      "学生的最大分为98\n",
      "学生的最小分为52\n",
      "高于平均分的学生\n",
      "学生4    96\n",
      "学生5    92\n",
      "学生6    98\n",
      "学生7    74\n",
      "dtype: int32\n",
      "Index(['学生4', '学生7', '学生9', '学生8', '学生3', '学生10', '学生6', '学生2', '学生5', '学生1'], dtype='object')\n"
     ]
    }
   ],
   "execution_count": 46
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-28T09:53:45.818580Z",
     "start_time": "2025-09-28T09:53:45.809519Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#练习二\n",
    "s = pd.Series(np.random.randint(100,251,10),index=pd.date_range('2025-09-28',periods=10))\n",
    "print(s)\n",
    "print(s.pct_change().sort_values(ascending=False).index[0])#获取最大最小的索引\n",
    "print(s.pct_change().idxmax())#获取最大最小的索引\n",
    "print(s.pct_change().idxmin())#获取最大最小的索引\n",
    "\n",
    "list1 = s.diff()>0\n",
    "print(list1)\n",
    "print(list1[list1.rolling(3).sum()==3].index)"
   ],
   "id": "307946bd2e442983",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2025-09-28    154\n",
      "2025-09-29    197\n",
      "2025-09-30    200\n",
      "2025-10-01    207\n",
      "2025-10-02    188\n",
      "2025-10-03    194\n",
      "2025-10-04    228\n",
      "2025-10-05    116\n",
      "2025-10-06    203\n",
      "2025-10-07    178\n",
      "Freq: D, dtype: int32\n",
      "2025-10-06 00:00:00\n",
      "2025-10-06 00:00:00\n",
      "2025-10-05 00:00:00\n",
      "2025-09-28    False\n",
      "2025-09-29     True\n",
      "2025-09-30     True\n",
      "2025-10-01     True\n",
      "2025-10-02    False\n",
      "2025-10-03     True\n",
      "2025-10-04     True\n",
      "2025-10-05    False\n",
      "2025-10-06     True\n",
      "2025-10-07    False\n",
      "Freq: D, dtype: bool\n",
      "DatetimeIndex(['2025-10-01'], dtype='datetime64[ns]', freq='D')\n"
     ]
    }
   ],
   "execution_count": 75
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-28T10:27:23.913030Z",
     "start_time": "2025-09-28T10:27:23.906081Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#案例三\n",
    "np.random.seed(42)\n",
    "s = pd.Series(np.random.randint(0,100,24),index= pd.date_range('2025-09-28',periods=24,freq=\"h\"))\n",
    "print(s)\n",
    "print(s.resample('D').sum())\n",
    "#s1 = s.between_time('08:00:00','22:00:00')\n",
    "s1 = s[(s.index.hour >=8)&(s.index.hour <=22)]\n",
    "print(s1.sum())#获取时间段内的数据\n",
    "s2 = s.drop(s1.index)\n",
    "print(s2.sum())\n",
    "print(s1.sum()/s2.sum())\n",
    "print(s.sort_values(ascending=False).head(3).index.tolist())#获取最大的三个索引"
   ],
   "id": "d8275289194da9e7",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2025-09-28 00:00:00    51\n",
      "2025-09-28 01:00:00    92\n",
      "2025-09-28 02:00:00    14\n",
      "2025-09-28 03:00:00    71\n",
      "2025-09-28 04:00:00    60\n",
      "2025-09-28 05:00:00    20\n",
      "2025-09-28 06:00:00    82\n",
      "2025-09-28 07:00:00    86\n",
      "2025-09-28 08:00:00    74\n",
      "2025-09-28 09:00:00    74\n",
      "2025-09-28 10:00:00    87\n",
      "2025-09-28 11:00:00    99\n",
      "2025-09-28 12:00:00    23\n",
      "2025-09-28 13:00:00     2\n",
      "2025-09-28 14:00:00    21\n",
      "2025-09-28 15:00:00    52\n",
      "2025-09-28 16:00:00     1\n",
      "2025-09-28 17:00:00    87\n",
      "2025-09-28 18:00:00    29\n",
      "2025-09-28 19:00:00    37\n",
      "2025-09-28 20:00:00     1\n",
      "2025-09-28 21:00:00    63\n",
      "2025-09-28 22:00:00    59\n",
      "2025-09-28 23:00:00    20\n",
      "Freq: h, dtype: int32\n",
      "2025-09-28    1205\n",
      "Freq: D, dtype: int32\n",
      "709\n",
      "496\n",
      "1.4294354838709677\n",
      "[Timestamp('2025-09-28 11:00:00'), Timestamp('2025-09-28 01:00:00'), Timestamp('2025-09-28 10:00:00')]\n"
     ]
    }
   ],
   "execution_count": 95
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-09T09:08:36.272429Z",
     "start_time": "2025-10-09T09:08:36.208711Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#dataframe学习\n",
    "s1 = pd.Series(np.random.randint(0,100,10))\n",
    "s2 = pd.Series(np.random.randint(0,100,10))\n",
    "df = pd.DataFrame({'MathScore':s1,'EnglishScore':s2})\n",
    "print(df)\n",
    "print(df.columns)\n",
    "print(df.index)\n",
    "print(df.values)\n",
    "print(df.dtypes)\n",
    "print(df.shape)\n",
    "print(df.size)\n",
    "print(df.count())\n",
    "print(df.isnull())\n",
    "print(df.isna())\n",
    "print(df.dropna())\n",
    "print(df.drop_duplicates())\n",
    "print(df.loc[4,'MathScore':'EnglishScore'])\n",
    "print(df.iloc[4,0:2])\n",
    "print(df.describe())\n",
    "print(df['MathScore'][df['MathScore']>80].index)"
   ],
   "id": "f1fac28c4edb4375",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   MathScore  EnglishScore\n",
      "0         93            37\n",
      "1         36            39\n",
      "2         34            32\n",
      "3         61            66\n",
      "4         90            73\n",
      "5         34            90\n",
      "6         58            18\n",
      "7         44            28\n",
      "8         21            66\n",
      "9         62            35\n",
      "Index(['MathScore', 'EnglishScore'], dtype='object')\n",
      "RangeIndex(start=0, stop=10, step=1)\n",
      "[[93 37]\n",
      " [36 39]\n",
      " [34 32]\n",
      " [61 66]\n",
      " [90 73]\n",
      " [34 90]\n",
      " [58 18]\n",
      " [44 28]\n",
      " [21 66]\n",
      " [62 35]]\n",
      "MathScore       int32\n",
      "EnglishScore    int32\n",
      "dtype: object\n",
      "(10, 2)\n",
      "20\n",
      "MathScore       10\n",
      "EnglishScore    10\n",
      "dtype: int64\n",
      "   MathScore  EnglishScore\n",
      "0      False         False\n",
      "1      False         False\n",
      "2      False         False\n",
      "3      False         False\n",
      "4      False         False\n",
      "5      False         False\n",
      "6      False         False\n",
      "7      False         False\n",
      "8      False         False\n",
      "9      False         False\n",
      "   MathScore  EnglishScore\n",
      "0      False         False\n",
      "1      False         False\n",
      "2      False         False\n",
      "3      False         False\n",
      "4      False         False\n",
      "5      False         False\n",
      "6      False         False\n",
      "7      False         False\n",
      "8      False         False\n",
      "9      False         False\n",
      "   MathScore  EnglishScore\n",
      "0         93            37\n",
      "1         36            39\n",
      "2         34            32\n",
      "3         61            66\n",
      "4         90            73\n",
      "5         34            90\n",
      "6         58            18\n",
      "7         44            28\n",
      "8         21            66\n",
      "9         62            35\n",
      "   MathScore  EnglishScore\n",
      "0         93            37\n",
      "1         36            39\n",
      "2         34            32\n",
      "3         61            66\n",
      "4         90            73\n",
      "5         34            90\n",
      "6         58            18\n",
      "7         44            28\n",
      "8         21            66\n",
      "9         62            35\n",
      "MathScore       90\n",
      "EnglishScore    73\n",
      "Name: 4, dtype: int32\n",
      "MathScore       90\n",
      "EnglishScore    73\n",
      "Name: 4, dtype: int32\n",
      "       MathScore  EnglishScore\n",
      "count  10.000000     10.000000\n",
      "mean   53.300000     48.400000\n",
      "std    24.161724     23.481435\n",
      "min    21.000000     18.000000\n",
      "25%    34.500000     32.750000\n",
      "50%    51.000000     38.000000\n",
      "75%    61.750000     66.000000\n",
      "max    93.000000     90.000000\n",
      "Index([0, 4], dtype='int64')\n"
     ]
    }
   ],
   "execution_count": 4
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-09T09:38:32.442494Z",
     "start_time": "2025-10-09T09:38:32.428996Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#练习四\n",
    "stud = pd.DataFrame({\"张三\":np.random.randint(0,100,3),\n",
    "                     \"李四\":np.random.randint(0,100,3),\n",
    "                     \"王五\":np.random.randint(0,100,3),\n",
    "                     \"赵六\":np.random.randint(0,100,3),\n",
    "                     \"孙七\":np.random.randint(0,100,3)\n",
    "                     },index=[\"语文\",\"英语\",\"数学\"],dtype=\"int\")\n",
    "print(stud)\n",
    "stud.loc['平均分']=stud.mean().round(0)\n",
    "stud.loc['总分']=stud.sum()\n",
    "stud_scores = stud.loc[[\"语文\",\"英语\",\"数学\"]]  # 排除刚添加的统计行\n",
    "high_performers = stud_scores.loc[:, (stud_scores.loc[\"数学\"] > 90) | (stud_scores.loc[\"英语\"] > 85)]\n",
    "print(\"高分学生:\")\n",
    "print(high_performers)"
   ],
   "id": "af6b1d30f68f1dbb",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "    张三  李四  王五  赵六  孙七\n",
      "语文  84  72  94   4  13\n",
      "英语  49  45  49  40  92\n",
      "数学  64  36  26  10  78\n",
      "高分学生:\n",
      "      孙七\n",
      "语文  13.0\n",
      "英语  92.0\n",
      "数学  78.0\n"
     ]
    }
   ],
   "execution_count": 19
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-09T09:50:26.096452Z",
     "start_time": "2025-10-09T09:50:26.087836Z"
    }
   },
   "cell_type": "code",
   "source": [
    " #练习五\n",
    "data = {\n",
    "    '产品名称': ['手机', '电脑', '鼠标', '键盘'],\n",
    "    '单价': [500, 800, 30, 50],\n",
    "    '销量': [10, 5, 20, 15]\n",
    "}\n",
    "df = pd.DataFrame(data)\n",
    "print(df)\n",
    "df[\"总销售额\"] = df[\"单价\"]*df[\"销量\"]\n",
    "print(df.sort_values(by=\"总销售额\",ascending=False))\n",
    "print()\n",
    "print(df[df[\"总销售额\"]==df[\"总销售额\"].max()].产品名称)\n",
    "print(df.sort_values(by=\"总销售额\",ascending=False))"
   ],
   "id": "93b63309a9c6a866",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  产品名称   单价  销量\n",
      "0   手机  500  10\n",
      "1   电脑  800   5\n",
      "2   鼠标   30  20\n",
      "3   键盘   50  15\n",
      "  产品名称   单价  销量  总销售额\n",
      "0   手机  500  10  5000\n",
      "1   电脑  800   5  4000\n",
      "3   键盘   50  15   750\n",
      "2   鼠标   30  20   600\n",
      "\n",
      "0    手机\n",
      "Name: 产品名称, dtype: object\n",
      "  产品名称   单价  销量  总销售额\n",
      "0   手机  500  10  5000\n",
      "1   电脑  800   5  4000\n",
      "3   键盘   50  15   750\n",
      "2   鼠标   30  20   600\n"
     ]
    }
   ],
   "execution_count": 29
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-09T10:02:28.122943Z",
     "start_time": "2025-10-09T10:02:28.115113Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#练习六\n",
    "data = {\n",
    "    '用户ID': [1001, 1002, 1003, 1004, 1005],\n",
    "    '用户名': ['张三', '李四', '王五', '赵六', '孙七'],\n",
    "    '商品类别': ['手机', '电脑', '手机', '键盘', '鼠标'],\n",
    "    '购买数量': [2, 1, 3, 1, 2],\n",
    "    '商品价格': [500, 800, 300, 50, 30]\n",
    "}\n",
    "df = pd.DataFrame(data)\n",
    "print(df)\n",
    "df['总销售额'] = df['购买数量'] * df['商品价格']\n",
    "print(df.nlargest(1, '总销售额'))\n",
    "print(df.总销售额.mean())\n",
    "print(df[df['商品类别']=='手机'].购买数量.sum())"
   ],
   "id": "78c97a0957ff55de",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   用户ID 用户名 商品类别  购买数量  商品价格\n",
      "0  1001  张三   手机     2   500\n",
      "1  1002  李四   电脑     1   800\n",
      "2  1003  王五   手机     3   300\n",
      "3  1004  赵六   键盘     1    50\n",
      "4  1005  孙七   鼠标     2    30\n",
      "   用户ID 用户名 商品类别  购买数量  商品价格  总销售额\n",
      "0  1001  张三   手机     2   500  1000\n",
      "562.0\n",
      "5\n"
     ]
    }
   ],
   "execution_count": 32
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
